package com.wt.wechatTools;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.wt.wechatTools.databinding.FragmentSystemSetupBinding;
import com.wt.wechatTools.room.WorkRepository;
import com.wt.wechatTools.room.entity.ContactsEntity;
import com.wt.wechatTools.room.entity.UserEntity;
import com.wt.wechatTools.tools.MyRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FragmentSystemSetup extends Fragment {
    private static final String TAG = "FragmentSystemSetup";
    private WorkRepository workRepository;
    private AlertDialog alertDialog;
    private UserEntity userEntity;


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        FragmentSystemSetupBinding binding;
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_system_setup, container, false);


        workRepository = new WorkRepository(getContext());
        /**
         * 获取用户基础信息
         */
        workRepository.getUserLive().observe(getActivity(), new Observer<UserEntity>() {
            @Override
            public void onChanged(UserEntity ue) {
                userEntity = ue;
                if (userEntity == null) {
                    return;
                }

                //更新按钮
                switch (userEntity.getRole()) {
                    case 1:
                        binding.btnUpdateContacts.setVisibility(View.GONE);
                        binding.btnLogout.setVisibility(View.GONE);
                        break;
                    case 2:
                        binding.btnUpdateContacts.setVisibility(View.VISIBLE);
                        binding.btnLogout.setVisibility(View.VISIBLE);
                }

                //设置cdk按钮
                String endTime = userEntity.getEndTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date ed = dateFormat.parse(endTime);
                    Date nowDate = new Date();
                    if (ed.getTime() > nowDate.getTime()) {
                        binding.btnCDK.setVisibility(View.GONE);
                    } else {
                        binding.btnCDK.setVisibility(View.VISIBLE);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                switch (userEntity.getCount()) {
                    case 10:
                        binding.spTaskNumber.setSelection(0);
                        break;
                    case 15:
                        binding.spTaskNumber.setSelection(1);
                        break;
                    case 20:
                        binding.spTaskNumber.setSelection(2);
                        break;
                    case 25:
                        binding.spTaskNumber.setSelection(3);
                        break;
                    case 100:
                        binding.spTaskNumber.setSelection(4);
                        break;
                }

                switch (userEntity.getSpeed()) {
                    case 1000:
                        binding.spTaskSpeed.setSelection(0);
                        break;
                    case 1500:
                        binding.spTaskSpeed.setSelection(1);
                        break;
                    case 2000:
                        binding.spTaskSpeed.setSelection(2);
                        break;
                    case 3000:
                        binding.spTaskSpeed.setSelection(3);
                        break;
                }
            }
        });

        /**
         * 保存用户基础数据
         */
        binding.btnSaveSeting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //准备数据
                Log.d(TAG, "onClick: " + binding.spTaskNumber.getSelectedItem().toString());
                Log.d(TAG, "onClick: " + binding.spTaskSpeed.getSelectedItem().toString());
                Integer ct = Integer.parseInt(String.valueOf(binding.spTaskNumber.getSelectedItem()));
                Integer sp = Integer.parseInt(String.valueOf(binding.spTaskSpeed.getSelectedItem()));
                userEntity.setCount(ct);
                userEntity.setSpeed(sp);
                userEntity.setDataSource(binding.editDataSource.getText().toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        workRepository.updateUser(userEntity);
                        Looper.prepare();
                        Toast.makeText(getContext(), "保存设置成功！", Toast.LENGTH_SHORT).show();
                        Looper.loop();// 进入loop中的循环，查看消息队列
                    }
                }).start();
            }
        });

        //准备提示框
        alertDialog = new AlertDialog.Builder(getContext()).create();
        alertDialog.setTitle("提示");
        alertDialog.setMessage("你确定要清除所有名单？");
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //清除所有数据
                        workRepository.deleteContactsEntityAll();
                        Looper.prepare();
                        Toast.makeText(getContext(), "清除名单数据成功！", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                }).start();
            }
        });

        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        /**
         * 清除 所有名单数据
         */
        binding.btnDeleteAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.show();
            }
        });

        /**
         * 更新无效数据
         */
        binding.btnUpdateContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateContactsHttps();
            }
        });

        /**
         * 输入CDK
         */
        binding.btnCDK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转至充值界面
                NavController nv = Navigation.findNavController(v);
                nv.navigate(R.id.fragmentCdk);
            }
        });

        /**
         * 登录
         */
        binding.btnSysLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转至充值界面
                NavController nv = Navigation.findNavController(v);
                nv.navigate(R.id.fragmentLogin);
            }
        });

        /**
         * 退出登录
         */
        binding.btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userEntity.setUserName("");
                userEntity.setToken("");
                userEntity.setRole(1);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        workRepository.updateUser(userEntity);
                    }
                }).start();
            }
        });

        return binding.getRoot();
    }

    /**
     * 更新数据中心的数据
     * 删除无效的名单
     */
    private void updateContactsHttps() {
        JSONArray jsonArray = new JSONArray();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //获取用户信息
                List<ContactsEntity> cL = workRepository.getContactsByState(3);
                if (cL.size() == 0) {
                    Log.d(TAG, "run: 没有需要更新的数据！");
                    Looper.prepare();
                    Toast.makeText(getContext(), "没有需要更新的数据！！", Toast.LENGTH_LONG).show();
                    Looper.loop();// 进入loop中的循环，查看消息队列
                    return;
                }
                try {
                    for (ContactsEntity ce : cL) {
                        JSONObject jb = new JSONObject();
                        jb.put("id", ce.getId().toString());
                        jsonArray.put(jb);
                    }
                    Log.d(TAG, "run: " + jsonArray.toString());
                    // https://blog.csdn.net/xxl6097/article/details/51075400
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("jsonId", String.valueOf(jsonArray))
                            .add("register_token", MyRequest.register_token)
                            .build();
                    Request request = new Request.Builder()
                            .url(MyRequest.proUrl + "updateContacts")
                            .post(requestBody)
                            //增加关闭连接，不让它保持连接。https://blog.csdn.net/zhangteng22/article/details/52233126
                            .addHeader("Connection", "close")
                            .build();
                    Response res = null;
                    try {
                        res = okHttpClient.newCall(request).execute();
                        if (res.isSuccessful()) {
                            Log.d(TAG, "updateIDC: 更新 成功！");
                            //删除本地数据
                            for (ContactsEntity cn : cL) {
                                workRepository.deleteContactNormal(cn);
                            }
                            Looper.prepare();
                            Toast.makeText(getContext(), "更新 成功！", Toast.LENGTH_LONG).show();
                            Looper.loop();// 进入loop中的循环，查看消息队列
                        } else {
                            Log.d(TAG, "updateIDC: 更新 失败！");
                            Looper.prepare();
                            Toast.makeText(getContext(), "更新 失败！", Toast.LENGTH_LONG).show();
                            Looper.loop();// 进入loop中的循环，查看消息队列
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        res.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
}

